package com.anche.cywebnew.Utils.enums;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anche.cywebnew.Utils.String.StringUtils;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Pattern;
// import java.util.stream.Collectors;


@Component
public class EnumUtil {
    private static final Logger logger = LoggerFactory.getLogger(EnumUtil.class);

    /**
     * checkDeal 检测xml中在枚举中存在的值是否为空、是否符合要求
     * @param enumClass 用于检测的枚举
     * @param param json
     * @param name 返回的提示信息开头名称
     * */
    public static String checkDeal(Class<? extends Enum<?>> enumClass, JSONObject param, String name){
        return doCheck(enumClass, param, name);
    }

    public static String doCheck(Class<? extends Enum<?>> enumClass, JSONObject param, String name){
        JSONObject jsonObject = param;

        try {
            Map<String, Map<String, Object>> allFieldsAndValues = getAllFieldsAndValues(enumClass);
            for (String s : allFieldsAndValues.keySet()) {
                Map<String, Object> stringObjectMap = allFieldsAndValues.get(s);
                String field = String.valueOf(stringObjectMap.get("field"));

                if (StringUtils.isBlank(field)){
                    continue;
                }
                if (field.equals("ALL")){
                    Set<String> strings = jsonObject.keySet();
                    for (String string : strings) {
                        String text = Objects.toString(string, "");

                        String checkNull = checkNull(name, text, stringObjectMap);
                        if (!StringUtils.isBlank(checkNull)) {
                            return checkNull;
                        }
                    }
                    continue;
                }
                String vehispara = Objects.toString(jsonObject.get(field), "");
                String checkNull = checkNull(name, vehispara, stringObjectMap);
                if (!StringUtils.isBlank(checkNull)) {
                    return checkNull;
                }
            }
        }catch (Exception e){
            logger.error("通过枚举类型检验<"+ name +">时出现异常：" + JSON.toJSONString(e));
            return null;
        }

        return null;
    }
    static String checkNull(String name, String text, Map<String, Object> stringObjectMap ){
        String field = String.valueOf(stringObjectMap.get("field"));
        String message = String.valueOf(stringObjectMap.get("message"));
        String regex = String.valueOf(stringObjectMap.get("regex"));
        String regexMessage = String.valueOf(stringObjectMap.get("regexMessage"));
        boolean notNull = (boolean) stringObjectMap.get("notNull");
        String[] dictionary = (String[]) stringObjectMap.get("dictionary");

        if (StringUtils.isBlank(text)){
            if (!notNull){
                return null;
            }
            return name + "异常:"+message+ "<" +field+">" + "不能为空！";
        }else{
            String regexAndDictionary = regexAndDictionary(name, message, regex, regexMessage, text, dictionary);
            if (!StringUtils.isBlank(regexAndDictionary)){
                return regexAndDictionary;
            }
        }
        return null;
    }
    static String regexAndDictionary(String name, String message, String regex, String regexMessage,String text,String[] dictionary){
        if (!StringUtils.isBlank(regex) && !regex.equals("null") && !Pattern.matches(regex, text)){
            return name + "异常:"+message+"不符合要求！" + regexMessage + "异常值<" +text+">。";
        }
        if (dictionary != null && dictionary.length > 0){
            if (!Arrays.asList(dictionary).contains(text)) {
                return name + "异常:" + message + "不符合要求！只能是[" + Joiner.on(",").join(dictionary) + "]" + "异常值<" +text+">。";
            }
        }
        return null;
    }
    /**
     * 遍历枚举类的所有常量、字段和值
     *
     * @param enumClass 枚举类
     * @return 包含枚举常量名称、字段名称和字段值的Map
     */
    public static Map<String, Map<String, Object>> getAllFieldsAndValues(Class<? extends Enum> enumClass) {
        Map<String, Map<String, Object>> result = new HashMap<>();
        for (Enum<?> enumConstant : enumClass.getEnumConstants()) {
            Map<String, Object> enumConstantMap = new HashMap<>();
            for (Field field : enumClass.getDeclaredFields()) {
                try {
                    field.setAccessible(true);
                    Object value = field.get(enumConstant);
                    enumConstantMap.put(field.getName(), value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            result.put(enumConstant.name(), enumConstantMap);
        }
        return result;
    }
}
